package com.qf.service.impl;

import com.qf.entity.AdminEntity;
import com.qf.mapper.AdminMapper;
import com.qf.pojo.AdminPojo;
import com.qf.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    AdminMapper adminMapper;

    /**
     * 管理员登录
     * @param ae
     * @return 查询到这个管理员的权限信息
     */
    @Override
    public AdminPojo adminLogin(AdminEntity ae) {
        return adminMapper.adminLogin(ae);
    }

    @Override
    public List<AdminPojo> queryAdmins(AdminEntity ae) {
        return adminMapper.queryAdmins(ae);
    }

    /**
     * 根据用户ids删除用户信息
     * @param ids 用户ids
     * @return 删除结果; true:删除成功
     */
    @Override
    public boolean delAdminByIds(String ids) {
        String str = "("+ids.substring(0,ids.length()-1)+")";

        return adminMapper.delAdmin(str);
    }

    @Override
    public boolean delAdmin(int aid){

        String str = "("+aid+")";

        return adminMapper.delAdmin(str);
    }



    @Override
    public boolean addAdmin(AdminEntity ae) {

        boolean result = adminMapper.addAdmin(ae);

        if(result){
            String[] roles = ae.getRoles();
            for(String rid : roles){
                adminMapper.bindAdminRole(Integer.parseInt(rid),ae.getAid());
            }
        }
        return true;
    }

    @Override
    public boolean editAdmin(AdminEntity ae) throws Exception {
        //1:将当前用户的信息进行修改;

        boolean result = adminMapper.editAdmin(ae);

        if(!result){
            throw new Exception("修改用户失败");
        }

        //2: 对用户的角色信息进行重新绑定

        //2.1 删除用户的所有角色信息

        boolean rs = adminMapper.unbindAdminRole(ae.getAid());

        boolean flag;
        for(String rid : ae.getRoles()){
            flag = adminMapper.bindAdminRole(Integer.parseInt(rid),ae.getAid());

            if(!flag){
                throw new Exception("绑定用户角色失败");
            }
        }
        return true;
    }

    @Override
    public boolean qiyong(AdminEntity ae) {
        return adminMapper.editAdmin(ae);
    }
}
